package com.azt.provider.impl;

import com.azt.api.dto.*;
import com.azt.api.enums.ApplyCompanyAuditStateEnum;
import com.azt.api.enums.UserEnum;
import com.azt.api.exception.IncorrectCredentialsException;
import com.azt.api.exception.LockedAccountException;
import com.azt.api.exception.MailNotActiveException;
import com.azt.api.exception.UnknownAccountException;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.exception.BaseException;
import com.azt.model.FrontGlobals;
import com.azt.model.IforgotConstant;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.*;
import com.azt.utils.AESUtil;
import com.azt.utils.CommonUtil;
import com.azt.utils.PasswordUtil;
import com.azt.utils.PatternUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private CompanySignService companySignService;
	
	@Autowired
	private OldUserMapper oldUserMapper;

	@Autowired
	private MqProducerService mqProducerService;

	@Autowired
	private UserApplyCompanyMapper userApplyCompanyMapper;

	@Autowired
	private UserPermissionService userPermissionService;
    
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired
	private UserAccountMapper userAccountMapper;
	
	@Autowired
	private MsgConfigService msgConfigService;
	
	@Autowired
	private MsgUserService msgUserService;

	@Autowired
	private ConfigService configService;

	@Autowired
	private LoginLogMapper loginLogMapper;

	@Override
	public int getIndexUserCount() {
		return userMapper.getIndexUserCount();
	}

	@Override
	public Pagination getUserPageBy(int pageno,int pagesize,Map<String, String> searchMap) {
		Map param = new HashMap();
		String userinfo = searchMap.get("so_userinfo");
		if(StringUtils.isNotBlank(userinfo)) {
			userinfo = userinfo.trim();
			if(PatternUtils.isMobile(userinfo)) {
				param.put("mobile", userinfo);
			} else if(PatternUtils.isEmail(userinfo)) {
				param.put("email", userinfo);
			} else {
				param.put("username", userinfo);
			}
		}

		/**
		 * 采购商或者供应商
		 * 0全部
		 * 1采购商
		 * 2供应商
		 * 3采购商,供应商
		 * */
		String userrole = searchMap.get("so_userrole");
		int cg = 0;
		if(StringUtils.isNotBlank(userrole)) {
			cg = Integer.parseInt(userrole);
		}

		switch (cg) {
			case 0:
				break;
			case 1:
				param.put("ispurchaser", 1);
				break;
			case 2:
				param.put("isprovider", 1);
				break;
			case 3:
				param.put("ispurchaser", 1);
				param.put("isprovider", 1);
				break;
			default:
				break;
		}

		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<UserCompany> userList = userMapper.searchUser(param);

		Pagination p = new Pagination(startPage, userList);
		p.setList(userList);
		p.setParams(searchMap);
		return p;
	}

	@Override
	public User getFullUserById(int userId) {
		User user = userMapper.selectByPrimaryKey(userId);
		if(user != null) {
			if(user.getCompanyId() != null && user.getCompany() == null) {
				Company company = companyMapper.selectByPrimaryKey(user.getCompanyId());
				user.setCompany(company);
			}
			List<Role> roleList = userPermissionService.findRoleByUserId(user.getId());		//该用户所属的角色
			user.setRoles(roleList);
		}
		return user;
	}

	@Override
	public User getUserById(Integer userid) {
		User user = new User();
		user.setId(userid);
		return userMapper.selectOne(user);
	}

	@Override
	public void saveOrUpdate(User user) {
		if(user != null) {
			if(user.getId() == null) {
				userMapper.insert(user);
			} else {
				userMapper.updateByPrimaryKey(user);//null会被更新
			}
		}
	}

	@Override
	public void resetPassword(Integer userid ,String password) {
		User user = new User();
		user.setId(userid);
		String salt = PasswordUtil.getRandomSalt(6);
		user.setSalt(salt);
		user.setPassword(PasswordUtil.encodePasswordForAZT(password, salt));
		user.setUpdatetime(new Date());
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public User getUserByMobile(String mobile) {
		User user = new User();
		user.setMobile(mobile);
		user.setRemoved(0);
		return userMapper.selectOne(user);
	}

	@Override
	public User getUserByEmail(String email) {
		User user = new User();
		user.setEmail(email);
		user.setRemoved(0);
		return userMapper.selectOne(user);
	}

	@Override
	public User getUserByUserName(String username) {
		User user = null;
		if(StringUtils.isNotBlank(username)) {
			if(PatternUtils.isEmail(username)) {
				user = getUserByEmail(username);
			} else if(PatternUtils.isMobile(username)) {
				user = getUserByMobile(username);
			}
		}
		return user;
	}

	@Override
	public User registerNoAuth(String username, String password, String realName, Integer companyId, int roleId,String contactTel) throws BaseException {
		if(StringUtils.isNoneBlank(username, password)) {
			User existUser = null;
			try {
				existUser = checkUserNameForRegister(username);
			} catch (BaseException e) {
				throw e;
			}
			if(existUser == null) {
				try {
					//该用户名可注册
					User user = new User();
					if (PatternUtils.isMobile(username)) {
						user.setMobile(username);
					} else {
						user.setEmail(username);
						String authString = UUID.randomUUID().toString();
						user.setAuthString(authString);
						user.setMailActive(1);        //直接激活成功
					}
					String salt = PasswordUtil.getRandomSalt(6);
					user.setSalt(salt);
					user.setPassword(PasswordUtil.encodePasswordForAZT(password, salt));
					user.setCompanyId(companyId);
					user.setRegistertime(new Date());
					user.setRealName(realName);
					user.setState(1);
					user.setRemoved(0);
					user.setCreatetime(new Date());
					user.setContactTel(contactTel);
					saveOrUpdate(user);

					//判断如果没有就创建
					UserRole userRole = userPermissionService.getUserRoleByRoleId(roleId, user.getId());
					if(userRole==null){
						Role role1=userPermissionService.getRoleByCode("cadmin");
						Role role2=userPermissionService.getRoleByCode("padmin");
						Role role3=userPermissionService.getRoleByCode("cleader");
						Role role4=userPermissionService.getRoleByCode("pleader");
						if(role1.getId().equals(roleId)||role2.getId().equals(roleId)){
							userPermissionService.insertUserRole(user.getId(), role1.getId());
							userPermissionService.insertUserRole(user.getId(), role2.getId());
						}else if(role3.getId().equals(roleId)||role4.getId().equals(roleId)){
							userPermissionService.insertUserRole(user.getId(), role3.getId());
							userPermissionService.insertUserRole(user.getId(), role4.getId());
						}else{
							userPermissionService.insertUserRole(user.getId(), roleId);
						}
					}
				
					return user;
				} catch (Exception e) {
					LOGGER.error("registerNoAuth error", e);
					throw new BaseException("注册失败");
				}
			}
		}
		return null;
	}

	@Override
	public User verifyLogin(String username, String password) throws Exception {
		if(StringUtils.isNoneBlank(username, password)) {
			User user = getUserByUserName(username.trim());
			if(user == null) {
				throw new UnknownAccountException();    //帐号不存在
			}
			if(!PasswordUtil.checkPassword(password, user.getSalt(), user.getPassword())) {
				throw new IncorrectCredentialsException();  //密码不正确
			}
			if(user.getState() != 1) {
				throw new LockedAccountException(); //帐号被禁用
			}
			//邮箱登录的且邮箱未激活
			Integer mailActive = CommonUtil.safeToInteger(user.getMailActive(), 0);
			if(PatternUtils.isEmail(username.trim()) && (mailActive == null || mailActive != 1)) {
				throw new MailNotActiveException(user); //邮箱未激活
			}
			return user;
		}
		return null;
	}

	@Override
	public User checkUserNameForRegister(String username) throws BaseException {
		User user = null;
		try {
			if (StringUtils.isBlank(username)) {
				throw new BaseException("请输入手机号或邮箱");
			}

			username = username.trim();
			if (PatternUtils.isMobile(username)) {
				//手机号
				//检测该手机号是否已被注册
				user = getUserByUserName(username);
				if (user != null) {
					throw new BaseException("手机号已被注册，请<a href='javascript:void(0)' onclick=\"toLogin('" + username + "')\" style='color:#00a8e6;'>登录</a>");
				}
			} else if (PatternUtils.isEmail(username)) {
				//邮箱
				//检测该邮箱是否已被注册，若已被注册，则检测邮箱的激活状态
				user = getUserByUserName(username);
				if (user != null) {
					throw new BaseException(
							(user.getMailActive() != null && user.getMailActive().equals(1))
									? "该邮箱已注册，请<a href='javascript:void(0)' onclick=\"toLogin('" + username + "')\" style='color:#00a8e6;'>登录</a>"
									: "该邮箱已经注册但尚未激活，<a href='javascript:void(0)' onclick=\"toLogin('" + username + "')\" style='color:#00a8e6;'>登录激活</a>");
				}
			} else {
				throw new BaseException("手机/邮箱格式不正确，请重新输入");
			}
		} catch (Exception e) {
			if(e instanceof BaseException) {
				throw e;
			} else {
				e.printStackTrace();
				throw new BaseException("未知错误");
			}
		}
		return user;
	}

	@Override
	public OldUser getOldUserById(Integer userid) {
		return oldUserMapper.selectByPrimaryKey(userid);
	}

	@Override
	public void sendIforgotMail(String email, String pwdString) {
		try {
			String webSite = configService.getConfigValueByCode("WEB_SITE");
			String _code = createIforgotMailCode(email, pwdString);
			String iforgotUrl = "http://" + webSite + "/user/iforgotEmail?username=" + URLEncoder.encode(email, "utf-8") + "&code=" + URLEncoder.encode(_code, "utf-8");
			LOGGER.info("iforgot email url:" + iforgotUrl);

			File template = ResourceUtils.getFile("classpath:/template/iforgotMail.html");
			String content = FileUtils.readFileToString(template, "utf-8");

			content = content.replace("#webSite#", webSite);
			content = content.replace("#url#", iforgotUrl);
			content = content.replace("#time#", CommonUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm"));
			content = content.replace("#username#", email);

			MailParam mailParam = new MailParam();
			mailParam.setSubject("您在安装通的登录密码重新设定");
			mailParam.setContent(content);
			mailParam.setTo(email);
			mailParam.setFrom("安装通");
			mqProducerService.sendMailMessage(mailParam);
		} catch (Exception e) {
			LOGGER.error("iforgot mail error", e);
		}
	}

	@Override
	public String createIforgotMailCode(String email, String pwdString) {
		//生成找回密码url（u_user表中pwdString|email|当前时间|过期时间|iforgot 经过AES加密而成，密钥为IforgotConstant.EMAIL_KEY）
		String createString = CommonUtil.formatDate(new Date(), "yyyyMMddHHmmss");
		String expireString = CommonUtil.formatDate(DateUtils.addDays(new Date(), 1), "yyyyMMddHHmmss");
		return AESUtil.encrypt(pwdString + "|" + email + "|" + createString + "|" + expireString + "|iforgot", IforgotConstant.EMAIL_KEY);
	}

	@Override
	public void sendActiveMail(String email, String authString) {
		try {
			String webSite = configService.getConfigValueByCode("WEB_SITE");

			String _code = createActiveMailCode(email, authString);

			File template = ResourceUtils.getFile("classpath:/template/activeMail.html");
			String content = FileUtils.readFileToString(template, "utf-8");

			content = content.replace("#webSite#", webSite);
			content = content.replace("#url#", "http://" + webSite + "/user/activeMail?username=" + URLEncoder.encode(email, "utf-8") + "&code=" + URLEncoder.encode(_code, "utf-8"));
			content = content.replace("#time#", CommonUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm"));

			MailParam mailParam = new MailParam();
			mailParam.setSubject("欢迎注册成为安装通的会员");
			mailParam.setContent(content);
			mailParam.setTo(email);
			mailParam.setFrom("安装通");
			mqProducerService.sendMailMessage(mailParam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String createActiveMailCode(String email, String authString) {
		//生成邮箱激活码（u_user表中authString|邮箱|当前时间|过期时间 经过AES加密而成，密钥为Globals.ACTIVEMAIL_KEY）
		String createString = CommonUtil.formatDate(new Date(), "yyyyMMddHHmmss");
		String expireString = CommonUtil.formatDate(DateUtils.addDays(new Date(), 2), "yyyyMMddHHmmss");	//有效期48小时
		return AESUtil.encrypt(authString + "|" + email + "|" + createString + "|" + expireString, FrontGlobals.ACTIVEMAIL_KEY);
	}

	@Override
	public void deleteById(Integer userid){
		User user = new User();
		user.setId(userid);
		user.setRemoved(1);
		userMapper.updateByPrimaryKeySelective(user);
	}
	
    @Override
    public void toggleUserDisabledById(Integer userid) {
    	User user = userMapper.selectByPrimaryKey(userid);
		if(user != null) {
			User _user = new User();
			_user.setId(userid);
			int state = user.getState();
			if(state == 0) {
				_user.setState(1);
			} else if(state == 1) {
				_user.setState(0);
			}
			userMapper.updateByPrimaryKeySelective(_user);
		}
    }

    @Override
    public void insertUserApplyCompany(UserApplyCompany uac) {
		uac.setCreatetime(new Date());
		userApplyCompanyMapper.insert(uac);
	}

	@Override
	public List<UserApplyCompany> findUserApplyCompanyByUserId(int userId, Integer auditState) {
		Map param = new HashMap();
		param.put("userId", userId);
		param.put("auditState", auditState);
		return userApplyCompanyMapper.findApplyCompanyByUserId(param);
	}

	@Override
	public UserApplyCompany getAuditingApplyCompany(int userId) {
		List<UserApplyCompany> list = findUserApplyCompanyByUserId(userId, ApplyCompanyAuditStateEnum.INIT.getValue());
		return (list != null && list.size() > 0) ? list.get(0) : null;
	}

	@Override
	public List<User> getUserByAdminRole(Integer companyId, List<Role> ifAdminRole) {
		return userMapper.getUserByAdminRole(companyId,ifAdminRole);
	}

	@Override
	public Pagination getFrontUserPageByCid(int pageno, int pagesize, Map<String, String> params) {
		Page<Object> startPage=PageHelper.startPage(pageno, pagesize);
		List<UserVO> frontUserList=userMapper.queryPageUserListByCompanyId(params);
		Pagination p=new Pagination(startPage, frontUserList);
		p.setList(frontUserList);
		return p;
	}

	@Override
	public Integer queryApplyUserCount(String companyId, String roletype) {
		return userMapper.queryApplyUserCount(companyId, roletype);
	}

	@Override
	public void unbindUserFromCompany(String userid) {
		UserRole r=new UserRole();
		r.setUserId(CommonUtil.safeToInteger(userid));
		userRoleMapper.delete(r);
		
		Role role=new Role();
		UserRole r2=new UserRole();
		role.setCode("register");
		r2.setUserId(CommonUtil.safeToInteger(userid));
		r2.setRoleId(roleMapper.selectOne(role).getId());
		r2.setCreatetime(new Date());
		r2.setUpdatetime(new Date());
		userRoleMapper.insertSelective(r2);
		
		userMapper.unbindUserFromCompany(userid);
	}

	@Override
	public int queryRoleByCompanyId(String companyId,String roleType) {
		return userMapper.queryRoleByCompanyId(companyId,roleType);
	}

	@Override
	public User queryUserBylogin(String login) {
		return userMapper.queryUserBylogin(login);
	}

	@Override
	public List<Role> findRoleByCompanyId(Company company, int roleType) {
		List<Role> list = new ArrayList<>();
		if(company != null) {
			if(company.getParentId() == null) {
				Role adminRole = userPermissionService.getRoleByCode(roleType == 1 ? "cadmin" : "padmin");
				if (adminRole != null) {
					list.add(adminRole);
				}
			}

			Role role = new Role();
			role.setCompanyId(company.getId());
			role.setRoleType(roleType);
			role.setRemoved(0);
			List<Role> roles = roleMapper.select(role);
			if (CollectionUtil.isNotEmpty(roles)) {
				list.addAll(roles);
			}
		}
		return list;
	}

	@Override
	public List<Role> getRolesByCompanyId(Integer companyId,Integer roleType) {
		Role role=new Role();
		role.setCompanyId(companyId);
		if(roleType != null) {
			role.setRoleType(roleType);
		}
		role.setIfAdmin(0);
		List<Role> roleList=roleMapper.select(role);
		
		Company com=new Company();
		com.setId(companyId);
		if(companyMapper.selectByPrimaryKey(com).getParentId()==null){
			Role r2=new Role();
			r2.setIfDefault(1);
			if(roleType != null) {
				r2.setRoleType(roleType);
			}
			r2.setIfAdmin(1);
			List<Role> rlist=roleMapper.select(r2);
			for(Role r:rlist){
				roleList.add(r);
			}
		}
		return roleList;
	}

	@Override
	public void addEmployee(User user,Company company,int roleId,String roleCode) {
		Boolean isMoblieLogin=true;
		StringBuffer buff=new StringBuffer();
		if(StringUtils.isNotBlank(user.getEmail())){
			buff.append(user.getEmail());
			isMoblieLogin=false;
		}else{
			buff.append(user.getMobile());
		}
		try {
			//String password=RandomStringUtils.randomAlphanumeric(8);
			String password=String.valueOf((int)((Math.random()*9+1)*100000));
			if(user.getId()==null){
				User u= registerNoAuth(buff.toString(), password, user.getRealName(), company.getId(), roleId,user.getContactTel());
				if(u!=null){
					Map<String, String> params=new HashMap<String, String>();
					params.put("companyName", company.getCompanyName());
					params.put("password", password);
					if(isMoblieLogin){
						params.put("account", user.getMobile());
						msgConfigService.sendMessage("ADD_USER", params, null, u.getId());
					}else{
//						MailParam mp=new MailParam();
//						mp.setTo(user.getEmail());
//						mp.setContent("dsdadasdadasd");
//						mp.setSubject("安装通");
//						mqProducerService.sendMailMessage(mp);
						params.put("account", user.getEmail());
						msgConfigService.sendMessage("ADD_USER", params, null, u.getId());
					}
					if("padmin".equals(roleCode)){
						msgUserService.insertByUserAndCompany(u.getId(), company.getId());
					}
				}
			}else{
				addNoCompanyEmployee(user,company,roleId);
				Map<String, String> params=new HashMap<String, String>();
				params.put("companyName", company.getCompanyName());
				msgConfigService.sendMessage("ADD_NCUSER", params, null, user.getId());
				if("padmin".equals(roleCode)){
					msgUserService.insertByUserAndCompany(user.getId(),company.getId());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	@Override
	public void addNoCompanyEmployee(User user, Company company, int roleId) {
		User u=new User();
		u.setId(user.getId());
		u.setCompanyId(company.getId());
		u.setContactTel(user.getContactTel());
		u.setRealName(user.getRealName());
		userMapper.updateByPrimaryKeySelective(u);
		
		UserRole role=new UserRole();
		role.setUserId(user.getId());
		userRoleMapper.delete(role);
		
		Role role1=userPermissionService.getRoleByCode("cadmin");
		Role role2=userPermissionService.getRoleByCode("padmin");
		Role role3=userPermissionService.getRoleByCode("cleader");
		Role role4=userPermissionService.getRoleByCode("pleader");
		if(role1.getId().equals(roleId)||role2.getId().equals(roleId)){
			userPermissionService.insertUserRole(user.getId(), role1.getId());
			userPermissionService.insertUserRole(user.getId(), role2.getId());
		}else if(role3.getId().equals(roleId)||role4.getId().equals(roleId)){
			userPermissionService.insertUserRole(user.getId(), role3.getId());
			userPermissionService.insertUserRole(user.getId(), role4.getId());
		}else{
			userPermissionService.insertUserRole(user.getId(), roleId);
		}
	}

	@Override
	public void updateEmpoyee(User u,int originRoleid,Company company,String roleCode) {
		 //1交接
		 User originalUser=userMapper.selectByPrimaryKey(u);
		 String originUserEmail=originalUser.getEmail();
		 String originUserMobile=originalUser.getMobile();
		 String login=u.getMobile()==null?u.getEmail():u.getMobile();
		 if(!login.equals(originUserMobile)&&!login.equals(originUserEmail)){//begin
			 User userNow=userMapper.queryUserBylogin(login);
			 if(userNow==null){//修改的新账号并未注册的情况下
				 User insertUser=new User();
				 insertUser.setMobile(u.getMobile());
				 insertUser.setEmail(u.getEmail());
				 insertUser.setRemoved(0);
				 userMapper.insertSelective(insertUser);
				 
				 User userNow2=userMapper.queryUserBylogin(login);
				 Role role=new Role();
				 UserRole r2=new UserRole();
				 role.setCode("register");
				 r2.setUserId(userNow2.getId());
				 r2.setRoleId(roleMapper.selectOne(role).getId());
				 r2.setCreatetime(new Date());
				 r2.setUpdatetime(new Date());
				 userRoleMapper.insertSelective(r2);
					
				 Integer changeUserID=originalUser.getId();
				 Integer changeCompanyID=originalUser.getCompanyId();
				 originalUser.setId(userNow2.getId());
				 originalUser.setCompanyId(null);
				 originalUser.setUpdatetime(new Date());
				 userMapper.updateByPrimaryKey(originalUser);
				 
				 originalUser.setId(changeUserID);
				 originalUser.setMobile(u.getMobile());
				 originalUser.setEmail(u.getEmail());
				 originalUser.setCompanyId(changeCompanyID);
				 String salt = PasswordUtil.getRandomSalt(6);
				 originalUser.setSalt(salt);
				 String showPAW=String.valueOf((int)((Math.random()*9+1)*100000));
				 originalUser.setPassword(PasswordUtil.encodePasswordForAZT(showPAW, salt));
				 userMapper.updateByPrimaryKey(originalUser);
				 
				 Map<String, String> params=new HashMap<String, String>();
				 params.put("companyName", company.getCompanyName());
				 params.put("password", showPAW);
				 if(u.getMobile()!=null){
					 params.put("account", u.getMobile());
					 msgConfigService.sendMessage("ADD_USER", params, null, originalUser.getId());
				 }else{
					 params.put("account", u.getEmail());
					 msgConfigService.sendMessage("ADD_USER", params, null, originalUser.getId());
				 }
				 if("padmin".equals(roleCode)){
					 msgUserService.insertByUserAndCompany(originalUser.getId(),company.getId());
				 }
			 }else{//已注册
				 User userNow2=userMapper.queryUserBylogin(login);
				 Integer changeUserID=originalUser.getId();
				 originalUser.setId(userNow2.getId());
				 originalUser.setCompanyId(null);
				 originalUser.setUpdatetime(new Date());
				 userMapper.updateByPrimaryKey(originalUser);
				 
				 userNow2.setId(changeUserID);
				 userNow2.setCompanyId(company.getId());
				 userMapper.updateByPrimaryKey(userNow2);
				 
				 Map<String, String> params=new HashMap<String, String>();
				 params.put("companyName", company.getCompanyName());
				 if(u.getMobile()!=null){
					msgConfigService.sendMessage("ADD_NCUSER", params, null, userNow2.getId());
				 }else{
					msgConfigService.sendMessage("ADD_NCUSER", params, null, userNow2.getId());
				 }
				 if("padmin".equals(roleCode)){
					 msgUserService.insertByUserAndCompany(userNow2.getId(),company.getId());
				 }
			 }
		 }
		 //2
		 UserRole r= userRoleMapper.getUserRoleByRoleId(originRoleid,u.getId());
		 r.setRoleId(u.getRoleId());
		 userRoleMapper.updateByPrimaryKeySelective(r);
		 if(u.getRealName()!=null||u.getContactTel()!=null){
			 userMapper.updateByPrimaryKeySelective(u);
		 }
	}
	
	public List<User> getUsersByUserRoles(List<UserRole> userRoles) {
		List<User> users=new ArrayList<User>();
		if(userRoles!=null && userRoles.size()>0){
			for(UserRole usr:userRoles){
				User userById = this.getUserById(usr.getUserId());
				if(userById!=null){
					users.add(userById);
				}
			}
		}
		return users;

	}

	@Override
	public Pagination getApplyEmployee(int pageno, int pagesize, String companyId, String roleType) {
		Page<Object> startPage=PageHelper.startPage(pageno, pagesize);
		List<UserApplyVO> userApplyList=userApplyCompanyMapper.getApplyEmployee(companyId, roleType);
		Pagination p=new Pagination(startPage, userApplyList);
		p.setList(userApplyList);
		return p;
	}

	@Override
	public UserApplyCompany getUserApplyCompanyByUid(Integer uid) {
		UserApplyCompany ua=new UserApplyCompany();
		ua.setUserId(uid);
		ua.setAuditState(0);
		return userApplyCompanyMapper.selectOne(ua);
	}

	@Override
	public void agreeUserApply(UserApplyCompany u) {
		UserApplyCompany ua=new UserApplyCompany();
		ua.setId(u.getId());
		ua.setAuditState(u.getAuditState());
		ua.setRoleId(u.getRoleId());
		userApplyCompanyMapper.updateByPrimaryKeySelective(ua);
		
		User user=new User();
		user.setId(u.getUserId());
		user.setCompanyId(u.getCompanyId());
		user.setRealName(u.getRealName());
		userMapper.updateByPrimaryKeySelective(user);
		
		
		UserRole ur=new UserRole();
		ur.setUserId(u.getUserId());
		userRoleMapper.delete(ur);
		
		ur.setRoleId(u.getRoleId());
		userRoleMapper.insert(ur);
	}

	@Override
	public void refuseUserApply(UserApplyCompany u) {
		UserApplyCompany uap=new UserApplyCompany();
		uap.setId(u.getId());
		uap.setAuditState(2);
		uap.setAuditOpinion(u.getAuditOpinion());
		userApplyCompanyMapper.updateByPrimaryKeySelective(uap);
	}

	@Override
	public Map getUserInfo(Company company, Role currentRole,User currentuser) {
		Map mapinfo=new HashMap();
		//获取用户身份
		CompanySign companySign = companySignService.getCompanySign(company.getId(),2,true);
		mapinfo.put("companySign", companySign);
		//账户积分
		UserAccount useraccount=this.getUserAccountByUserId(currentuser.getId());
		mapinfo.put("userAccount", useraccount);

		return mapinfo;
	}


	public UserAccount getUserAccountByUserId(Integer userId){
		UserAccount ua=new UserAccount();
		ua.setUserId(userId);
		return userAccountMapper.selectOne(ua);
	}

	@Override
	public List<UserAuthority> getUserAuthorityByCompanyId(Integer companyId, List<UserEnum> userenum) {
		List<UserEnum> newenum=new ArrayList();
		List<UserAuthority> userAuthorityAdmin=null;
		if(userenum!=null && userenum.size()>0){
			for(UserEnum usn:userenum){
				if(usn.getIfAdmin()==1){//如果有管理员返回管理员的user
					newenum.add(usn);
					userAuthorityAdmin = userMapper.getUserAuthorityAdminByCompanyId(companyId);//获取管理员的user数据
					break;
				}
			}

			userenum.remove(newenum);//移除
			List<UserAuthority> userAuthority = userMapper.getUserAuthorityByCompanyId(companyId,userenum);
			if(userAuthorityAdmin!=null && userAuthorityAdmin.size()>0){
				userAuthorityAdmin.addAll(userAuthority);
			}
			return userAuthority;
		}else{
			return null;
		}
	}

	@Override
	public boolean getUserAuthorityByUserId(Integer userId, List<UserEnum> userenum) {
		//判断user是否管理员返回true,否则去查
		boolean flag=false;
		List<Role> findRole = userPermissionService.findRoleByUserId(userId);
		if(findRole!=null && findRole.size()>0){
			for(Role rl:findRole){
				if(rl.getIfAdmin()==1){
					return true;
				}
			}
			
			//非管理员user进入下面
			if(userenum!=null && userenum.size()>0){
				for(UserEnum usn:userenum){
					if(usn.getIfAdmin()==1){
						flag= false;//非管理员没有权限管理员的权限
					}
				}
				
				//去掉管理员的菜单
			  Iterator it = userenum.iterator();  
			  while(it.hasNext()){  
			        	UserEnum ue = (UserEnum)it.next();  
			        	if(ue.getIfAdmin()==1){
							userenum.remove(ue);
					}
			    }
				
				UserAuthority userAuthority = userMapper.getUserAuthorityByUserId(userId,userenum);
				if(userAuthority!=null){
					flag= true;
				}else{
					flag= false;
				}
				return flag;
			}else{
				return false;
			}
			
		}else{//没角色
			return false;
		}
	
	}

	@Override
	public List<UserApplyCompany> getUserApplyCompanyByRoleId(Integer companyId, Integer roleId,Integer auditState) {
		return userApplyCompanyMapper.getUserApplyCompanyByRoleId(companyId,roleId,auditState);
	}

	@Override
	public void changeRoleByUserId(Integer userId, Integer roleId,Integer orRoleId) {
		UserRole ur=new UserRole();
		ur.setUserId(userId);
		ur.setRoleId(orRoleId);
		UserRole r2= userRoleMapper.selectOne(ur);
		r2.setRoleId(roleId);
		userRoleMapper.updateByPrimaryKeySelective(r2);
	}

	@Override
	public void forbiddenUser(Integer userId,Integer state) {
		User u=new User();
		u.setId(userId);
		u.setState(state==0?1:0);
		userMapper.updateByPrimaryKeySelective(u);
	}

	@Override
	public List<UserForEcharts> echartsAdded() {
		return userMapper.echartsAdded();
	}

	@Override
	public List<UserForEcharts> echartsAddedAuth() {
		return userMapper.echartsAddedAuth();
	}

    @Override
    public User getUserByQuoteId(Integer quoteId) {
        return userMapper.getUserByQuoteId(quoteId);
    }

	@Override
	public List<UserExt> getAllLeaderIds(String code) {
		return userMapper.getAllLeaderIds(code);
	}

	@Override
	public UserForMonthTip getUserForMonthTip(Integer userid, String code, Integer year, Integer month) {
		return userMapper.getUserForMonthTip(userid,code,year,month);
	}

	@Override
	public List<User> getUsersBYCompanyId(Integer companyId) {
		User u = new User();
		u.setCompanyId(companyId);
		u.setRemoved(0);
		return userMapper.select(u);
	}

    @Override
    public List<LoginLog> findLoginLogByUserId(int userId) {
		LoginLog loginLog = new LoginLog();
		loginLog.setUserId(userId);
		return loginLogMapper.select(loginLog);
	}

	@Override
	public LoginLog getLoginLog(String sessionId, int userId) {
		if(StrUtil.isNotBlank(sessionId)) {
			LoginLog loginLog = new LoginLog();
			loginLog.setSessionId(sessionId);
			loginLog.setUserId(userId);
			return loginLogMapper.selectOne(loginLog);
		}
		return null;
	}

	@Override
	public void insertLoginLog(LoginLog loginLog) {
		if(loginLog != null) {
			loginLogMapper.insertSelective(loginLog);
		}
	}

	@Override
	public void updateLoginLog(LoginLog loginLog) {
		if(loginLog != null) {
			loginLogMapper.updateByPrimaryKeySelective(loginLog);
		}
	}
	
	@Override
	public List<User> getUserByIngralRecord(String recordTime) {
		return userMapper.getUserByIngralRule(recordTime);
	}

	@Override
	public List<Map> statisticsUser(Map param) {
		return userMapper.statisticsUser(param);
	}

	@Override
	public List<Map> statisticsUserDetail(Map param) {
		return userMapper.statisticsUserDetail(param);
	}
}
